<?php
/**
 * @package Spider Contacts
 * @author Web-Dorado
 * @copyright (C) 2012 Web-Dorado. All rights reserved.
 * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
 **/
 
defined('_JEXEC') or die('Restricted access');
require_once(JApplicationHelper::getPath('admin_html'));
$task	= JRequest::getCmd('task'); 
$option=JRequest::getVar('option', '');
JTable::addIncludePath(JPATH_ADMINISTRATOR . DS . 'components' . DS . $option . DS . 'tables');
if (isset($_REQUEST['controller']))
    $controller = $_REQUEST['controller'];
else
    $controller = 'show_links';
$op_type = JRequest::getVar('op_type', '');
switch ($task)

{
		case 'export_csv':
		if ($controller == 'contacts')
		{
			export_csv($option);
			}
			break;

	case 'back_to_messages':
			if ($controller == 'messages')
			{
				back_to_messages($option);
				}
				break;
			
	case 'markUnreaden':
			if ($controller == 'messages')
			
			{
				markUnreaden($option);
				}
				break;
	case 'markReaden':
			if ($controller == 'messages')
			{
				markReaden($option);
				}
			break;
    case 'edit':
    case 'add':
        if ($controller == 'contacts')
          {
            editContact($option);
          }
        if ($controller == 'category')
            editCategory($option);
        break;
    case 'apply':
	case 'save':
        if ($controller == 'category')
            saveCategory($option, $task);
        if ($controller == 'contacts')
            saveContact($option, $task);
        if ($controller == 'options')
          {
            if ($op_type == "global")
                saveGlobal($option, $task);
            if ($op_type == "styles")
                saveStyles($option, $task);
			if ($op_type == "message_options")
                saveMessageOptions($option, $task);
				
          }
		  break;
		    case 'saveorder':
     
        if ($controller == 'contacts')
             saveOrderContact($cid);
        if ($controller == 'category')
            saveOrderCategories($cid);
        break;
		case 'cancel':
        cancel($option, $controller);
        break;
    case 'remove':
        if ($controller == 'contacts')
            removeContact($option);
        if ($controller == 'category')
            removeCategory($option, $task);
		 if ($controller == 'messages')
            removeMessages($option);
			case 'publish':
        if ($controller == 'contacts')
            publishContacts($option);
        if ($controller == 'category')
            publishCategory($option, $task);
			
			
        break;
		
		  case 'view':
		  if ($controller == 'messages')
            viewMessage($option);
			break;
		
    case 'unpublish':
        if ($controller == 'contacts')
            unpublishContacts($option);
        if ($controller == 'category')
            unpublishCategory($option, $task);
        break;
		 default:
        if ($controller == 'contacts')
		{
			JSubMenuHelper::addEntry(JText::_('Categories'), 'index.php?option=com_spidercontacts&amp;controller=category' );
			JSubMenuHelper::addEntry(JText::_('Contacts'), 'index.php?option=com_spidercontacts&amp;controller=contacts', true );
			JSubMenuHelper::addEntry(JText::_('Messages'), 'index.php?option=com_spidercontacts&amp;controller=messages' );
			JSubMenuHelper::addEntry(JText::_('Options'), 'index.php?option=com_spidercontacts&amp;controller=options' );
            showContacts($option, $controller);
		}
		if ($controller == 'messages')
		{	JSubMenuHelper::addEntry(JText::_('Categories'), 'index.php?option=com_spidercontacts&amp;controller=category' );
			JSubMenuHelper::addEntry(JText::_('Contacts'), 'index.php?option=com_spidercontacts&amp;controller=contacts' );
			JSubMenuHelper::addEntry(JText::_('Messages'), 'index.php?option=com_spidercontacts&amp;controller=messages', true );
			JSubMenuHelper::addEntry(JText::_('Options'), 'index.php?option=com_spidercontacts&amp;controller=options' );
            showMessages($option, $controller);
		}
        if ($controller == 'options')
          {
			  JSubMenuHelper::addEntry(JText::_('Categories'), 'index.php?option=com_spidercontacts&amp;controller=category' );
			JSubMenuHelper::addEntry(JText::_('Contacts'), 'index.php?option=com_spidercontacts&amp;controller=contacts' );
			JSubMenuHelper::addEntry(JText::_('Messages'), 'index.php?option=com_spidercontacts&amp;controller=messages' );
			JSubMenuHelper::addEntry(JText::_('Options'), 'index.php?option=com_spidercontacts&amp;controller=options', true );
            showOptions($option, $controller, $op_type);
            if ($op_type == 'global')
                showglobal($option, $controller, $op_type);
            if ($op_type == 'styles')
                showStyles($option, $controller, $op_type);
			if ($op_type == 'message_options')
                showMessageOptions($option, $controller, $op_type);
			  
          }
        if ($controller == 'category')
		{	 JSubMenuHelper::addEntry(JText::_('Categories'), 'index.php?option=com_spidercontacts&amp;controller=category', true );
			JSubMenuHelper::addEntry(JText::_('Contacts'), 'index.php?option=com_spidercontacts&amp;controller=contacts' );
			JSubMenuHelper::addEntry(JText::_('Messages'), 'index.php?option=com_spidercontacts&amp;controller=messages' );
			JSubMenuHelper::addEntry(JText::_('Options'), 'index.php?option=com_spidercontacts&amp;controller=options' );
            showCategory($option, $controller);
		}
        if ($controller == 'show_links')
          {
            showLinks($option, $controller);
          }
        break;
}


function showLinks($option, $controller)
  {
    HTML_spidercontacts::showLinks($option, $controller);
  }
  ////////edit product
function editContact($option)
  {
    JRequest::setVar('hidemainmenu', 1);
    $params =& JComponentHelper::getParams('com_spidercontacts');
    $params->merge($itemparams);
    $doc =& JFactory::getDocument();
    $plugin_js_path = JURI::root(true) . '/administrator/components/com_spidercontacts/js';
    $doc->addScript($plugin_js_path . "/param_block.js");
    $row =& JTable::getInstance('contacts', 'Table');
    $cid = JRequest::getVar('cid', array(
        0
    ), '', 'array');
    $id  = $cid[0];
    $row->load($id);
    $lists            = array();
    $category_id['0'] = array(
        'value' => '0',
        'text' => 'None Taken'
    );
    $db =& JFactory::getDBO();
    $query = "SELECT id,name FROM #__spidercontacts_contacts_categories where published=1";
    $db->setQuery($query);
    $rows1 = $db->loadObjectList();
    if ($db->getErrorNum())
      {
        echo $db->stderr();
        return false;
      }
    for ($i = 0, $n = count($rows1); $i < $n; $i++)
      {
        $row1 =& $rows1[$i];
        $id1               = $row1->id;
        $category_id[$id1] = array(
            'value' => $row1->id,
            'text' => $row1->name
        );
      }
    $ordering['0'] = array(
        'value' => '0',
        'text' => '0 First'
    );
    $db =& JFactory::getDBO();
    $query = "SELECT ordering,first_name, last_name FROM #__spidercontacts_contacts order by ordering";
    $db->setQuery($query);
    $rows1 = $db->loadObjectList();
    if ($db->getErrorNum())
      {
        echo $db->stderr();
        return false;
      }
    for ($i = 0, $n = count($rows1); $i < $n; $i++)
      {
        $row1 =& $rows1[$i];
        $ordering1            = $row1->ordering;
        $ordering[$ordering1] = array(
            'value' => $row1->ordering,
            'text' => ($row1->ordering . "(" . $row1->first_name . ")")
        );
      }
    $ordering[(count($rows1) + 1)] = array(
        'value' => (count($rows1) + 1),
        'text' => (count($rows1) + 1) . ' Last'
    );
    $lists['ordering']             = JHTML::_('select.genericList', $ordering, 'ordering', 'class="inputbox" ' . '', 'value', 'text', $row->ordering);
	$lists['category_id']          = JHTML::_('select.genericList', $category_id, 'category_id', 'class="inputbox"  onchange="submitbutton(\'apply\');"', 'value', 'text', $row->category_id);
    if (!$row->id)
        $pub = 1;
    else
        $pub = $row->published;
    $lists['published'] = JHTML::_('select.booleanlist', 'published', 'class="inputbox"', $pub);
	$db =& JFactory::getDBO();
	$query ="SELECT param FROM #__spidercontacts_contacts_categories where id='".$db->getEscaped($row->category_id)."'";
	$db->setQuery( $query );
	$rows1 = $db->loadObjectList();
	if ($db->getErrorNum()) 
		{
			echo $db->stderr();
			return false;
		}
    HTML_spidercontacts::editContact($row, $lists, $option, $params, $rows1);
  }
  
  
  ////////edit Category
function editCategory($option)
  {
    JRequest::setVar('hidemainmenu', 1);
    $doc =& JFactory::getDocument();
    $plugin_js_path = JURI::root(true) . '/administrator/components/com_spidercontacts/js';
    $doc->addScript($plugin_js_path . "/param_block.js");
    $row =& JTable::getInstance('categories', 'Table');
    $cid = JRequest::getVar('cid', array(
        0
    ), '', 'array');
    $id  = $cid[0];
    $row->load($id);
    $lists       = array();
    //parent category
    $parent['0'] = array(
        'value' => '0',
        'text' => 'Head'
    );
    $db =& JFactory::getDBO();
    $query = "SELECT id,name FROM #__spidercontacts_contacts_categories where id<>'".$db->getEscaped($row->id)."'";
    $db->setQuery($query);
    $rows1 = $db->loadObjectList();
    if ($db->getErrorNum())
      {
        echo $db->stderr();
        return false;
      }
    for ($i = 0, $n = count($rows1); $i < $n; $i++)
      {
        $row1 =& $rows1[$i];
        $id1          = $row1->id;
        $parent[$id1] = array(
            'value' => $row1->id,
            'text' => $row1->name
        );
      }
    $ordering['0'] = array(
        'value' => '0',
        'text' => '0 First'
    );
    $db =& JFactory::getDBO();
    $query = "SELECT ordering,name FROM #__spidercontacts_contacts_categories order by ordering";
    $db->setQuery($query);
    $rows1 = $db->loadObjectList();
    if ($db->getErrorNum())
      {
        echo $db->stderr();
        return false;
      }
    for ($i = 0, $n = count($rows1); $i < $n; $i++)
      {
        $row1 =& $rows1[$i];
        $ordering1            = $row1->ordering;
        $ordering[$ordering1] = array(
            'value' => $row1->ordering,
            'text' => ($row1->ordering . "(" . $row1->name . ")")
        );
      }
    $ordering[(count($rows1) + 1)] = array(
        'value' => (count($rows1) + 1),
        'text' => (count($rows1) + 1) . ' Last'
    );
    $lists['ordering']             = JHTML::_('select.genericList', $ordering, 'ordering', 'class="inputbox" ' . '', 'value', 'text', $row->ordering);
    $lists['parent']               = JHTML::_('select.genericList', $parent, 'parent', 'class="inputbox" ' . '', 'value', 'text', $row->parent);
    //
    if (!$row->id)
        $pub = 1;
    else
        $pub = $row->published;
    $lists['published'] = JHTML::_('select.booleanlist', 'published', 'class="inputbox"', $pub);
    HTML_spidercontacts::editCategory($row, $lists, $option);
  }

/////////////save Contact
function saveContact($option, $task)
  {
    $mainframe =& JFactory::getApplication();
    $db =& JFactory::getDBO();
    $row =& JTable::getInstance('contacts', 'Table');
    $first_name = JRequest::getVar('first_name', '', 'post', 'string', JREQUEST_ALLOWRAW);
	$last_name = JRequest::getVar('last_name', '', 'post', 'string', JREQUEST_ALLOWRAW);
    if ($first_name == "")
      {
        echo "<script> alert('First Name is empty');



	window.history.go(-1); </script>\n";
        exit();
      }
    if (!$row->bind(JRequest::get('post')))
      {
        echo "<script> alert('" . $row->getError() . "');



	window.history.go(-1); </script>\n";
        exit();
      }
	  
	  if ($last_name == "")
      {
        echo "<script> alert('Last Name is empty');



	window.history.go(-1); </script>\n";
        exit();
      }
    if (!$row->bind(JRequest::get('post')))
      {
        echo "<script> alert('" . $row->getError() . "');



	window.history.go(-1); </script>\n";
        exit();
      }
	  
	  
    $row->description = JRequest::getVar('description', '', 'post', 'string', JREQUEST_ALLOWRAW);

    if (!$row->store())
      {
        echo "<script> alert('" . $row->getError() . "');



	window.history.go(-1); </script>\n";
        exit();
      }
    $table =& JTable::getInstance('contacts', 'Table');
    $table->reorder();
    $id = JRequest::getVar('id', '', 'post');
    switch ($task)
    {
        case 'apply':
            $msg  = 'Changes to Contacts saved';
            $link = 'index.php?option=' . $option . '&task=edit&controller=contacts&cid[]=' . $row->id;
            break;
        case 'save':
        default:
            $msg  = 'Contact Saved';
            $link = 'index.php?option=' . $option . '&controller=contacts';
            break;
    }
    $mainframe->redirect($link, $msg);
  }
  
  /////////////save
function saveCategory($option, $task)
  {
    $mainframe =& JFactory::getApplication();
    $row =& JTable::getInstance('categories', 'Table');
    $name = JRequest::getVar('name', '', 'post', 'string', JREQUEST_ALLOWRAW);
    if ($name == "")
      {
        echo "<script> alert('Name is empty');



	window.history.go(-1); </script>\n";
        exit();
      }
    if (!$row->bind(JRequest::get('post')))
      {
        echo "<script> alert('" . $row->getError() . "');



	window.history.go(-1); </script>\n";
        exit();
      }
    if (!$row->store())
      {
        echo "<script> alert('" . $row->getError() . "');



	window.history.go(-1); </script>\n";
        exit();
      }
    $table =& JTable::getInstance('categories', 'Table');
    $table->reorder();
    switch ($task)
    {
        case 'apply':
            $msg  = 'Changes to Category saved';
            $link = 'index.php?option=' . $option . '&controller=category&task=edit&cid[]=' . $row->id;
            break;
        case 'save':
        default:
            $msg  = 'Category Saved';
            $link = 'index.php?option=' . $option . '&controller=category';
            break;
    }
    $mainframe->redirect($link, $msg);
  }
////////////Show
function showContacts($option, $controller)
  {
    $mainframe =& JFactory::getApplication();
    $db =& JFactory::getDBO();
    $table =& JTable::getInstance('contacts', 'Table');
    $table->reorder();
    $filter       = "";
    $ord          = JRequest::getVar('ord', 1);
    $filter_state = $mainframe->getUserStateFromRequest($option . '.filter_state', 'filter_state', '', 'word');
    if ($ord)
      {
        $filter_order_Dir = $mainframe->getUserStateFromRequest($option . '.filter_order_Dir', 'filter_order_Dir', '', 'word');
        $filter_order     = $mainframe->getUserStateFromRequest($option . '.filter_order', 'filter_order', 'ordering', 'cmd');
      }
    else
      {
        $filter_order_Dir = "asc";
        $filter_order     = "ordering";
      }
    //echo $filter_order_Dir;
    //echo $filter_state;
    $limit      = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
    $limitstart = $mainframe->getUserStateFromRequest($option . '.limitstart', 'limitstart', 0, 'int');
	
	
	
    $ord        = JRequest::getVar('ord', 1);
    if ($ord and ($filter_order == "first_name" or  $filter_order == "last_name" or $filter_order == "categories.name"  or $filter_order == "ordering" or $filter_order == "published"))
        $order = ' ORDER BY ' . $filter_order . ' ' . $filter_order_Dir . ', ordering';
    else
        $order = "";
    $lists            = array();
    $category_id['0'] = array(
        'value' => '0',
        'text' => '- Select a Category -'
    );
    $db =& JFactory::getDBO();
    $query = "SELECT id,name FROM #__spidercontacts_contacts_categories where published=1";
    $db->setQuery($query);
    $rows1 = $db->loadObjectList();
    if ($db->getErrorNum())
      {
        echo $db->stderr();
        return false;
      }
    $search     = $mainframe->getUserStateFromRequest($option . '.search', 'search', '', 'string');
    $search     = JString::strtolower($search);
    $cat_search = $mainframe->getUserStateFromRequest($option . '.cat_search', 'cat_search', '', 'string');
    $cat_search = JString::strtolower($cat_search);
    for ($i = 0, $n = count($rows1); $i < $n; $i++)
      {
        $row1 =& $rows1[$i];
        $id1               = $row1->id;
        $category_id[$id1] = array(
            'value' => $row1->id,
            'text' => $row1->name
        );
      }
    $lists['category_id'] = JHTML::_('select.genericList', $category_id, 'cat_search', 'class="inputbox" onchange="this.form.submit();"' . '', 'value', 'text', $cat_search);
	
	
	
    //echo  $lists['category_id'];
    //echo $search;
    if ($cat_search)
      {
        $filter .= ' where  #__spidercontacts_contacts.category_id=' . $db->getEscaped($cat_search, true);
      }
    if ($search)
      {
        if ($cat_search)
            $filter .= ' and ';
        else
            $filter .= ' where ';
        $filter .= ' LOWER(#__spidercontacts_contacts.first_name) OR LOWER(#__spidercontacts_contacts.last_name) LIKE ' . $db->Quote('%' . $db->getEscaped($search, true) . '%', false);
      }
    $query = 'SELECT COUNT(*)' . ' FROM #__spidercontacts_contacts ' . $db->getEscaped($filter);
    //echo		$query;
    $db->setQuery($query);
    $total = $db->loadResult();
    ///////////Paging//////////////////
    jimport('joomla.html.pagination');
    $pageNav = new JPagination($total, $limitstart, $limit);
    ///////////Paging//////////////////
    $query   = "SELECT #__spidercontacts_contacts.*,categories.name as category FROM #__spidercontacts_contacts left join #__spidercontacts_contacts_categories  as categories on  #__spidercontacts_contacts.category_id=categories.id " .$db->getEscaped($filter) . " $order";
    //echo $query;
    $db->setQuery($query, $pageNav->limitstart, $pageNav->limit);
    $rows = $db->loadObjectList();
    if ($db->getErrorNum())
      {
        echo $db->stderr();
        return false;
      }
    $lists['order_Dir'] = $filter_order_Dir;
    $lists['order']     = $filter_order;
    $lists['search']    = $search;
    HTML_spidercontacts::showContacts($option, $rows, $controller, $lists, $pageNav);
  }
  
  
  
  
  function showMessages($option, $controller)
  {
    $mainframe =& JFactory::getApplication();
    $db =& JFactory::getDBO();
    $table =& JTable::getInstance('messages', 'Table');
    $table->reorder();
    $filter       = "";
    $ord          = JRequest::getVar('ord', 1);

	
    $filter_state = $mainframe->getUserStateFromRequest($option . '.filter_state', 'filter_state', '', 'word');

    if ($ord)
      { 
        $filter_order_Dir = $mainframe->getUserStateFromRequest($option . '.filter_order_Dir', 'filter_order_Dir', '', 'word');
		$filter_order     = '`'.$mainframe->getUserStateFromRequest($option . '.filter_order', 'filter_order', 'date', 'cmd').'`';
	
      }
	 
    else
      {
		
        $filter_order_Dir = "asc";
        $filter_order     = "`date`";
      }
//  echo $filter_order;
 //  echo $filter_order_Dir;
    //echo $filter_state;
    $limit      = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
    $limitstart = $mainframe->getUserStateFromRequest($option . '.limitstart', 'limitstart', 0, 'int');
   
    if ($filter_order == "`first_name`" or $filter_order == "`last_name`"  or $filter_order == "`category.name`"  or $filter_order == "`date`" or $filter_order=="`sender`" or $filter_order=="`title`" )
        $order = ' ORDER BY ' . $filter_order . ' ' . $filter_order_Dir . '';
    else
        $order = "ORDER BY date";
    $lists            = array();
	$cat_lists            = array();
	$to_category['0'] = array(
        'value' => '0',
        'text' => '- Select a Category -'
    );
    $to_contact['0'] = array(
        'value' => '0',
        'text' => '- Select a Contact -'
    );
    $db =& JFactory::getDBO();
    $query = "SELECT id ,first_name, last_name FROM #__spidercontacts_contacts ";
    $db->setQuery($query);
    $rows1 = $db->loadObjectList();
    if ($db->getErrorNum())
      {
        echo $db->stderr();
        return false;
      }
	  
	   $query_cat = "SELECT id,name FROM #__spidercontacts_contacts_categories WHERE `published` = 1";
    $db->setQuery($query_cat);
    $rows_cat = $db->loadObjectList();
    if ($db->getErrorNum())
      {
        echo $db->stderr();
        return false;
      }
	  
	  
	  
    $search     = $mainframe->getUserStateFromRequest($option . '.search', 'search', '', 'string');
    $search     = JString::strtolower($search);
    $cont_search = $mainframe->getUserStateFromRequest($option . '.cont_search', 'cont_search', '', 'string');
    $cont_search = JString::strtolower($cont_search);
	$cat_search = $mainframe->getUserStateFromRequest($option . '.cat_search', 'cat_search', '', 'string');
	$cat_search = JString::strtolower($cat_search);
    for ($i = 0, $n = count($rows1); $i < $n; $i++)
      {
        $row1 =& $rows1[$i];
        $id1               = $row1->id;
		$name = ''.$row1->first_name.' '.$row1->last_name.'';
        $to_contact[$id1] = array(
            'value' => $row1->id,
            'text' => $name
        );
      }
	  
	  
	  for ($i = 0, $n = count($rows_cat); $i < $n; $i++)
      {
        $row_cat =& $rows_cat[$i];
        $id_cat               = $row_cat->id;
        $to_category[$id_cat] = array(
            'value' => $row_cat->id,
            'text' => $row_cat->name
        );
      }
	  
    $lists['to_contact'] = JHTML::_('select.genericList', $to_contact, 'cont_search', 'class="inputbox" onchange="this.form.submit();"' . '', 'value', 'text', $cont_search);
	$cat_lists['to_category'] = JHTML::_('select.genericList', $to_category, 'cat_search', 'class="inputbox" onchange="this.form.submit();"' . '', 'value', 'text', $cat_search);
	
	$lists['startdate']= JRequest::getVar('startdate', "");
	$lists['enddate']= JRequest::getVar('enddate', "");
	
    //echo  $lists['category_id'];
    //echo $search;
	$go= true;

	  if ($cont_search && $cat_search )
	  {
		  $filter .= '  WHERE to_contact=' . $db->getEscaped($cont_search, true).' AND  `category`.`id`=' .$db->getEscaped($cat_search, true).'';
		  $go= false;
		  }
	
	if ($go)
	{
   if ($cont_search)
      {
        $filter .= '  WHERE to_contact=' . $db->getEscaped($cont_search, true).'';
      }
	if ($cat_search)
      {
        $filter .= ' WHERE `category`.`id`=' . $db->getEscaped($cat_search, true).'';
      }
	  
	}
	
	  
	 
	  
	  
	  
    if ($search)
      {
        if ($cont_search || $cat_search )
            $filter .= ' and ';
        else
            $filter .= ' where ';
        $filter .= ' LOWER(title) OR LOWER(text) LIKE ' . $db->Quote('%' . $db->getEscaped($search, true) . '%', false);
      }
	  
	  
	  if($lists['startdate']!='' && $lists['enddate']!='' )
	  {
		   if ($cont_search || $cat_search )
            $filter .= ' and ';
        else
            $filter .= ' where ';
		  $filter .=' `date` between "'.$lists['startdate'].' 00:00:00" and "'.$lists['enddate'].' 23:59:59"';
		  }
		  else
		  {				
								
								if($lists['startdate']!='' || $lists['enddate']!='' )
										if ($cont_search || $cat_search )
           						 $filter .= ' AND ';
       					 else
           						$filter .= ' WHERE ';
			  if($lists['startdate']!='' )
			  				
	  						$filter .='  `date` BETWEEN "'.$lists['startdate'].'" AND CURRENT_TIMESTAMP';
  				if($lists['enddate']!='')
							
 							$filter .='  `date` BETWEEN "0001-05-04" AND "'.$lists['enddate'].'"';
								
		  }
		  
    $query = 'SELECT COUNT(*)' . ' FROM #__spidercontacts_messages  ' . $db->getEscaped($filter);
    //echo		$query;
    $db->setQuery($query);
    $total = $db->loadResult();
    ///////////Paging//////////////////
    jimport('joomla.html.pagination');
    $pageNav = new JPagination($total, $limitstart, $limit);
    ///////////Paging//////////////////
    $query   = "SELECT message.*, contact.first_name, contact.last_name, contact.id AS c_id, category.id AS cat_id, contact.ordering, category.published, category.ordering , category.description ,  contact.published,  category.name  FROM  (`#__spidercontacts_contacts` AS contact  RIGHT JOIN   `#__spidercontacts_messages` AS message  ON contact.id= message.to_contact) LEFT JOIN   `#__spidercontacts_contacts_categories` AS category  ON category.id=contact.category_id " .$db->getEscaped($filter) . " ".$order."";
 //   echo $query;
	
	
    $db->setQuery($query, $pageNav->limitstart, $pageNav->limit);
    $rows = $db->loadObjectList();
    if ($db->getErrorNum())
      {
        echo $db->stderr();
        return false;
      }
    $lists['order_Dir'] = $filter_order_Dir;
    $lists['order']     = $filter_order;
    $lists['search']    = $search;
    HTML_spidercontacts::showMessages($option, $rows, $controller, $lists, $cat_lists, $pageNav);
  }
  
  
  
  
  
  
function showCategory($option, $controller)
  {
    $mainframe =& JFactory::getApplication();
    $db =& JFactory::getDBO();
    $table =& JTable::getInstance('categories', 'Table');
    $table->reorder();
    $filter           = "";
    $filter_order_Dir = $mainframe->getUserStateFromRequest($option . '.filter_order_Dir', 'filter_order_Dir', '', 'word');
    $filter_order     = $mainframe->getUserStateFromRequest($option . '.filter_order', 'filter_order', 'ordering', 'cmd');
    $filter_state     = $mainframe->getUserStateFromRequest($option . '.filter_state', 'filter_state', '', 'word');
    //echo $filter_order_Dir;
    //echo $filter_state;
    $limit            = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
    $limitstart       = $mainframe->getUserStateFromRequest($option . '.limitstart', 'limitstart', 0, 'int');
    $ord              = JRequest::getVar('ord', 1);
    if ($ord and ($filter_order == "name" or $filter_order == "description" or $filter_order == "ordering" or $filter_order == "published"))
        $order = ' ORDER BY ' . $filter_order . ' ' . $filter_order_Dir . ', ordering';
    else
        $order = "";
    $lists  = array();
    $search = $mainframe->getUserStateFromRequest($option . '.search', 'search', '', 'string');
    $search = JString::strtolower($search);
    if ($search)
      {
        $filter .= 'where LOWER(name) LIKE ' . $db->Quote('%' . $db->getEscaped($search, true) . '%', false);
      }
    $query = 'SELECT COUNT(*)' . ' FROM #__spidercontacts_contacts_categories ' . $db->getEscaped($filter);
    $db->setQuery($query);
    $total = $db->loadResult();
    //$total=6;
    ///////////Paging//////////////////
    jimport('joomla.html.pagination');
    $pageNav = new JPagination($total, $limitstart, $limit);
    ///////////Paging//////////////////
    $db =& JFactory::getDBO();
    $query = "SELECT *  from #__spidercontacts_contacts_categories ".$db->getEscaped($filter)." $order ";
    $db->setQuery($query, $pageNav->limitstart, $pageNav->limit);
    $rows = $db->loadObjectList();
    if ($db->getErrorNum())
      {
        echo $db->stderr();
        return false;
      }
    $lists['order_Dir'] = $filter_order_Dir;
    $lists['order']     = $filter_order;
    $lists['search']    = $search;
    HTML_spidercontacts::showcategories($option, $rows, $controller, $lists, $pageNav);
  }
  /////////Remove
function removeContact($option)
  {
    $mainframe =& JFactory::getApplication();
   JRequest::checkToken() or jexit('Invalid Token');
    $cid = JRequest::getVar('cid', array(), '', 'array');
    $db =& JFactory::getDBO();
    if (count($cid))
      {
        $cids  = implode(',', $cid);
        $query = "DELETE FROM #__spidercontacts_contacts WHERE id IN ( ".$db->getEscaped($cids)." )";
		$query_rem_message = "DELETE FROM #__spidercontacts_messages WHERE to_contact IN ( ".$db->getEscaped($cids)." )";
        $db->setQuery($query);
		if (!$db->query())
          {
            echo "<script> alert('" . $db->getErrorMsg() . "');



	window.history.go(-1); </script>\n";
          }
		$db->setQuery($query_rem_message);
        if (!$db->query())
          {
            echo "<script> alert('" . $db->getErrorMsg() . "');



	window.history.go(-1); </script>\n";
          }
      }
    $mainframe->redirect('index.php?option=' . $option . '&controller=contacts');
  }
  
  function removeMessages($option)
  {
    $mainframe =& JFactory::getApplication();
    JRequest::checkToken() or jexit('Invalid Token');
    $cid = JRequest::getVar('cid', array(), '', 'array');
    $db =& JFactory::getDBO();
    if (count($cid))
      {
        $cids  = implode(',', $cid);
        $query = "DELETE FROM #__spidercontacts_messages WHERE id IN ( ".$db->getEscaped($cids)." )";
        $db->setQuery($query);
        if (!$db->query())
          {
            echo "<script> alert('" . $db->getErrorMsg() . "');



	window.history.go(-1); </script>\n";
          }
      }
    $mainframe->redirect('index.php?option=' . $option . '&controller=messages');
  }
  
function removeCategory($option)
  {
    $mainframe =& JFactory::getApplication();
    JRequest::checkToken() or jexit('Invalid Token');
    $cid = JRequest::getVar('cid', array(), '', 'array');
    $db =& JFactory::getDBO();
    if (count($cid))
      {
        $cids  = implode(',', $cid);
        $query = "DELETE FROM #__spidercontacts_contacts_categories WHERE id IN ( ".$db->getEscaped($cids)." )";
        $db->setQuery($query);
        if (!$db->query())
          {
            echo "<script> alert('" . $db->getErrorMsg() . "');



	window.history.go(-1); </script>\n";
          }
      }
    $mainframe->redirect('index.php?option=' . $option . '&controller=category');
  }
  /////publish
function publishContacts($option)
  {
    $mainframe =& JFactory::getApplication();
    JRequest::checkToken() or jexit('Invalid Token');
    $cid = JRequest::getVar('cid', array(), '', 'array');
    $db =& JFactory::getDBO();
    if (count($cid))
      {
        $cids  = implode(',', $cid);
        $query = "update   #__spidercontacts_contacts set published=1 WHERE id IN ( ".$db->getEscaped($cids)." )";
        $db->setQuery($query);
        if (!$db->query())
          {
            echo "<script> alert('" . $db->getErrorMsg() . "');



	window.history.go(-1); </script>\n";
          }
      }
    $mainframe->redirect('index.php?option=' . $option . '&controller=contacts');
  }
function publishCategory($option)
  {
    $mainframe =& JFactory::getApplication();
    JRequest::checkToken() or jexit('Invalid Token');
    $cid = JRequest::getVar('cid', array(), '', 'array');
    $db =& JFactory::getDBO();
    if (count($cid))
      {
        $cids  = implode(',', $cid);
        $query = "update   #__spidercontacts_contacts_categories set published=1 WHERE id IN ( ".$db->getEscaped($cids)." )";
        $db->setQuery($query);
        if (!$db->query())
          {
            echo "<script> alert('" . $db->getErrorMsg() . "');



	window.history.go(-1); </script>\n";
          }
      }
    $mainframe->redirect('index.php?option=' . $option . '&controller=category');
  }
/////unpublish
function unpublishContacts($option)
  {
    $mainframe =& JFactory::getApplication();
    JRequest::checkToken() or jexit('Invalid Token');
    $cid = JRequest::getVar('cid', array(), '', 'array');
    $db =& JFactory::getDBO();
    if (count($cid))
      {
        $cids  = implode(',', $cid);
        $query = "update   #__spidercontacts_contacts set published=0 WHERE id IN ( ".$db->getEscaped($cids)." )";
        $db->setQuery($query);
        if (!$db->query())
          {
            echo "<script> alert('" . $db->getErrorMsg() . "');



window.history.go(-1); </script>\n";
          }
      }
    $mainframe->redirect('index.php?option=' . $option . '&controller=contacts');
  }
function unpublishCategory($option)
  {
    $mainframe =& JFactory::getApplication();
    JRequest::checkToken() or jexit('Invalid Token');
    $cid = JRequest::getVar('cid', array(), '', 'array');
    $db =& JFactory::getDBO();
    if (count($cid))
      {
        $cids  = implode(',', $cid);
        $query = "update   #__spidercontacts_contacts_categories set published=0 WHERE id IN ( ".$db->getEscaped($cids)." )";
        $db->setQuery($query);
        if (!$db->query())
          {
            echo "<script> alert('" . $db->getErrorMsg() . "');



window.history.go(-1); </script>\n";
          }
      }
    $mainframe->redirect('index.php?option=' . $option . '&controller=category');
  }
function saveOrderContact(&$cid)
  {
    $mainframe =& JFactory::getApplication();
    // Check for request forgeries
    JRequest::checkToken() or jexit('Invalid Token');
    // Initialize variables
    $db =& JFactory::getDBO();
    $cid   = JRequest::getVar('cid', array(), '', 'array');
    $total = count($cid);
    $order = JRequest::getVar('order', array(
        0
    ), 'post', 'array');
    JArrayHelper::toInteger($order, array(
        0
    ));
    $row =& JTable::getInstance('contacts', 'Table');
    $groupings = array();
    // update ordering values
    for ($i = 0; $i < $total; $i++)
      {
        $row->load((int) $cid[$i]);
        // track sections
        //echo $row->ordering;
        if ($row->ordering != $order[$i])
          {
            $row->ordering = $order[$i];
            if (!$row->store())
              {
                JError::raiseError(500, $db->getErrorMsg());
              }
          }
      }
    $msg = JText::_('New ordering saved');
    $mainframe->redirect('index.php?option=com_spidercontacts&controller=contacts', $msg);
  }
function saveOrderCategories(&$cid)
  {
	
    $mainframe =& JFactory::getApplication();
    // Check for request forgeries
    JRequest::checkToken() or jexit('Invalid Token');
    // Initialize variables
    $db =& JFactory::getDBO();
    $cid   = JRequest::getVar('cid', array(), '', 'array');
    $total = count($cid);
    $order = JRequest::getVar('order', array(
        0
    ), 'post', 'array');
    JArrayHelper::toInteger($order, array(
        0
    ));
    $row =& JTable::getInstance('categories', 'Table');
    $groupings = array();
    // update ordering values
    for ($i = 0; $i < $total; $i++)
      {
        $row->load((int) $cid[$i]);
        // track sections
        //echo $row->ordering;
        if ($row->ordering != $order[$i])
          {
            $row->ordering = $order[$i];
            if (!$row->store())
              {
                JError::raiseError(500, $db->getErrorMsg());
              }
          }
      }
    $msg = JText::_('New ordering saved');
    $mainframe->redirect('index.php?option=com_spidercontacts&controller=category', $msg);
  }
function cancel($option, $controller)
  {
	
 
    $mainframe =& JFactory::getApplication();
			$op_type = JRequest::getVar('op_type', "");
            $mainframe->redirect('index.php?option=' . $option . '&controller=' . $controller.'');
      
  }
function showOptions($option, $controller, $op_type)
  {
    HTML_spidercontacts::showOptions($op_type);
  }
  
  //show global
function showGlobal($option, $controller, $op_type)
  {
    $mainframe =& JFactory::getApplication();
    $db =& JFactory::getDBO();
    $table =& JTable::getInstance('params ', 'Table');
    $lists = array();
    $db =& JFactory::getDBO();
    $query = "SELECT *  from #__spidercontacts_params ";
    $db->setQuery($query);
    $rows = $db->loadObjectList();
    if ($db->getErrorNum())
      {
        echo $db->stderr();
        return false;
      }
    $param_values = array();
    foreach ($rows as $row)
      {
        $key                = $row->name;
        $value              = $row->value;
        $param_values[$key] = $value;
      }
    $db =& JFactory::getDBO();
    
    HTML_spidercontacts::showGlobal($option, $param_values, $controller, $op_type);
  }
//show styles
function showStyles($option, $controller, $op_type)
  {
    $mainframe =& JFactory::getApplication();
    $db =& JFactory::getDBO();
    $table =& JTable::getInstance('params ', 'Table');
    $lists = array();
    $db =& JFactory::getDBO();
    $query = "SELECT *  from #__spidercontacts_params ";
    $db->setQuery($query);
    $rows = $db->loadObjectList();
    if ($db->getErrorNum())
      {
        echo $db->stderr();
        return false;
      }
    $param_values = array();
    foreach ($rows as $row)
      {
        $key                = $row->name;
        $value              = $row->value;
        $param_values[$key] = $value;
      }
    HTML_spidercontacts::showStyles($option, $param_values, $controller, $op_type);
  }

function showMessageOptions($option, $controller, $op_type)
  {
    $mainframe =& JFactory::getApplication();
    $db =& JFactory::getDBO();
    $table =& JTable::getInstance('params ', 'Table');
    $lists = array();
    $db =& JFactory::getDBO();
    $query = "SELECT *  from #__spidercontacts_params ";
    $db->setQuery($query);
    $rows = $db->loadObjectList();
    if ($db->getErrorNum())
      {
        echo $db->stderr();
        return false;
      }
    $param_values = array();
    foreach ($rows as $row)
      {
        $key                = $row->name;
        $value              = $row->value;
        $param_values[$key] = $value;
      }
    HTML_spidercontacts::showMessageOptions($option, $param_values, $controller, $op_type);
  }

function saveGlobal($option, $task)
  {
    $mainframe =& JFactory::getApplication();
    $db =& JFactory::getDBO();
    $params = JRequest::getVar('params', array(
        0
    ), '', 'array');
    $db =& JFactory::getDBO();
    foreach ($params as $key => $value)
      {
        $query = "UPDATE  #__spidercontacts_params SET value='".$db->getEscaped($value)."' WHERE name='".$db->getEscaped($key)."' ";
        $db->setQuery($query);
        if (!$db->query())
          {
            echo "<script> alert('" . $db->getErrorMsg() . "');
window.history.go(-1); </script>\n";
          }
      }
    switch ($task)
    {
        case 'apply':
            $msg  = 'Changes to global options saved';
            $link = 'index.php?option=' . $option . '&controller=options&op_type=global';
            break;
        case 'save':
        default:
            $msg  = 'Changes to global options  saved';
            $link = 'index.php?option=' . $option . '&controller=options';
            break;
    }
    $mainframe->redirect($link, $msg);
  }
function saveStyles($option, $task)
  {
    $mainframe =& JFactory::getApplication();
    $db =& JFactory::getDBO();
    $params = JRequest::getVar('params', array(
        0
    ), '', 'array');
    $db =& JFactory::getDBO();
    foreach ($params as $key => $value)
      {
        $query = "update  #__spidercontacts_params set  value='".$db->getEscaped($value)."' WHERE name='".$db->getEscaped($key)."' ";
        $db->setQuery($query);
        if (!$db->query())
          {
            echo "<script> alert('" . $db->getErrorMsg() . "');
window.history.go(-1); </script>\n";
          }
      }
    switch ($task)
    {
        case 'apply':
            $msg  = 'Changes to Styles saved';
            $link = 'index.php?option=' . $option . '&controller=options&op_type=styles';
            break;
        case 'save':
        default:
            $msg  = 'Changes to Styles  saved';
            $link = 'index.php?option=' . $option . '&controller=options';
            break;
    }
    $mainframe->redirect($link, $msg);
  }
  
  
  function saveMessageOptions($option, $task)
  {
    $mainframe =& JFactory::getApplication();
    $db =& JFactory::getDBO();
    $params = JRequest::getVar('params', array(
        0
    ), '', 'array');
    $db =& JFactory::getDBO();
    foreach ($params as $key => $value)
      {
        $query = "update  #__spidercontacts_params set  value='".$db->getEscaped($value)."' WHERE name='".$db->getEscaped($key)."'  ";
        $db->setQuery($query);
        if (!$db->query())
          {
            echo "<script> alert('" . $db->getErrorMsg() . "');
window.history.go(-1); </script>\n";
          }
      }
    switch ($task)
    {
        case 'apply':
            $msg  = 'Changes to Message Options saved';
            $link = 'index.php?option=' . $option . '&controller=options&op_type=message_options';
            break;
        case 'save':
        default:
            $msg  = 'Changes to Mesasge Options saved';
            $link = 'index.php?option=' . $option . '&controller=options';
            break;
    }
    $mainframe->redirect($link, $msg);
  }
  
function markReaden ($option)

{
	 $mainframe =& JFactory::getApplication();
  
    $cid = JRequest::getVar('cid', array(), '', 'array');
    $db =& JFactory::getDBO();
    if (count($cid))
      {
        $cids  = implode(',', $cid);
       	$query_mark_readen_messages = "UPDATE  `#__spidercontacts_messages` SET  `readen` =  '1' WHERE `id` IN ( ".$db->getEscaped($cids).")";
        $db->setQuery($query_mark_readen_messages);
		
		if (!$db->query())
          {
            echo "<script> alert('" . $db->getErrorMsg() . "');



	window.history.go(-1); </script>\n";
          }
		
      }
    $mainframe->redirect('index.php?option=' . $option . '&controller=messages');
	
	}
	
	
	function markUnreaden ($option)

{
	 $mainframe =& JFactory::getApplication();
  
    $cid = JRequest::getVar('cid', array(), '', 'array');
    $db =& JFactory::getDBO();
    if (count($cid))
      {
        $cids  = implode(',', $cid);
       	$query_mark_unread_messages = "UPDATE  `#__spidercontacts_messages` SET  `readen` =  '0' WHERE `id` IN (".$db->getEscaped($cids).")";
        $db->setQuery($query_mark_unread_messages);
		if (!$db->query())
          {
            echo "<script> alert('" . $db->getErrorMsg() . "');



	window.history.go(-1); </script>\n";
          }
		
      }
    $mainframe->redirect('index.php?option=' . $option . '&controller=messages');
	
	}
function viewMessage($option  )
  {
    $mainframe =& JFactory::getApplication();
    $db =& JFactory::getDBO();
    $cid = JRequest::getVar('cid', array(), '', 'array');
   	$query='SELECT * FROM #__spidercontacts_messages WHERE id='.$db->getEscaped($cid[0]).' ';
	$db->setQuery($query);
    $row = $db->loadObjectList();
	if ($db->getErrorNum())
      {
        echo $db->stderr();
        return false;
      }
	  $row1 =& $row[0];
	 $cont_id = $row1->to_contact;
	  
	$query='SELECT id, first_name, last_name, category_id FROM #__spidercontacts_contacts WHERE id= '.$db->getEscaped($cont_id).' ';
	$db->setQuery($query);
    $cont_row = $db->loadObjectList();
	if ($db->getErrorNum())
      {
        echo $db->stderr();
        return false;
      }
	  $row2 =&  $cont_row[0];
	 $cat_id = $row2->category_id;
	$query='SELECT id, name FROM #__spidercontacts_contacts_categories WHERE id='.$db->getEscaped($cat_id).' ';
	$db->setQuery($query);
	
    $cat_row = $db->loadObjectList();
	$row3 =& $cat_row[0]; 
	if ($db->getErrorNum())
      {
        echo $db->stderr();
        return false;
      }
	  	$sender             = $row1->sender;
		$sender_phone =  $row1->phone;
		$sender_mail = $row1->email;
		$sender_cont_pref = $row1->cont_pref;
	 	$title              = $row1->title;
        $text             = $row1->text;
        $date = $row1->date;
		$name = ''.$row2->first_name.' '.$row2->last_name.'';
		$category = $row3->name;
		$query_readen = "UPDATE  `#__spidercontacts_messages` SET  `readen` =  '1' WHERE `id`=".$db->getEscaped($cid[0])."";
		
		$db->setQuery($query_readen);
		$db->query();
		if ($db->getErrorNum())
      {
        echo $db->stderr();
        return false;
      }
		
		HTML_spidercontacts::viewMessage($option,$sender , $title,  $text ,$date , $name,  $category, $sender_phone, $sender_mail, $sender_cont_pref);


  
}

function back_to_messages($option)
{	
	$mainframe =& JFactory::getApplication();
	JRequest::checkToken() or jexit('Invalid Token');
	$mainframe->redirect('index.php?option=' . $option . '&controller=messages');
	
	
	
	}

?>